<?php
namespace frontend\modules\v1\models;

use common\models\Business;
use yii\base\Model;
use Yii;

/**
 * Register form
 */
class RegisterForm extends Model
{
    public $account;
    public $code;
    public $password;
    public $repassword;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /** 校验账号信息 */
            ['account', 'filter', 'filter' => 'trim'],
            ['account', 'required'],
            ['account', 'unique', 'targetClass' => '\common\models\Business', 'message' => '该手机号已经被占用.'],
            ['account', 'string', 'min' => 11, 'max' => 11],

            /** 验证码 必须 */
            ['code', 'filter', 'filter' => 'trim'],
            ['code', 'required'],

            /** 密码 必须 长度6-20*/
            ['password', 'required'],
            ['password', 'string', 'min' => 6, 'max' => 20],

            /** 校验密码是否相同 */
            ['repassword', 'compare', 'compareAttribute'=>'password', 'message'=>'两处输入的密码并不一致']
        ];
    }

    /**
     * Signs up.
     *
     * @return Business|null the saved model or null if saving fails
     */
    public function signup()
    {
        /** 校验数据的合法性 */
        if($this->validate()){
            $business = new Business();
            $business->account = $this->account;
            $business->setPassword($this->password);
            $business->generateAuthKey();
            if ($business->save()) {
                return $business;
            }
        }
        return null;
    }

    /**
     * 重置账号
     */
    public function resetAccount($business = null)
    {
        /** 校验数据的合法性 */
        if($this->validate() && $business) {
            $_business = $business;
            $_business->account = $this->account;
            $_business->setPassword($this->password);
            $_business->generateAuthKey();
            if ($_business->save(false)) {
                return $_business;
            }
        }
        return null;
    }
}
